package org.KeyCrafter.server.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.redis.ArrayRedisMessage;
import io.netty.handler.codec.redis.BulkStringRedisContent;
import io.netty.handler.codec.redis.RedisMessage;
import io.netty.util.internal.UnstableApi;
import org.KeyCrafter.server.session.ClientSession;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 服务端
 */
@UnstableApi
public class ArgumentsAggregator extends ChannelInboundHandlerAdapter {
    // 将解码的参数组合成完整并设置给 client
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof ArrayRedisMessage) {
            List<RedisMessage> msgList = ((ArrayRedisMessage) msg).children();
            // 为 client 设置解析到的参数
            ClientSession c = ctx.channel().attr(ClientSession.ATTRIBUTE_KEY).get();
            // 清理之前的参数
            c.resetArgAndCmd();
            c.setArgc(msgList.size());
            for (RedisMessage message : msgList) {
                String val = ((BulkStringRedisContent) message).content().toString(StandardCharsets.UTF_8);
                c.addArgv(val);
            }
            // 将设置好参数的 client 传到给下一个 handler
            ctx.fireChannelRead(c);
        }
    }
}

